package com.zang.blogz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zang.blogz.entity.ArticleTag;
import com.zang.blogz.mapper.ArticleTagMapper;
import com.zang.blogz.service.ArticleTagService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.github.vampireachao.stream.core.optional.Opp;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 朵橙i
 * @since 2022-06-17
 */
@Service
public class ArticleTagServiceImpl extends ServiceImpl<ArticleTagMapper, ArticleTag> implements ArticleTagService {

    @Override
    public List<ArticleTag> saveArticleTag(Integer articleId, List<Integer> tagIds, Boolean isAdd) {

        ArrayList<ArticleTag> articleTags = new ArrayList<>();

        if (Opp.ofColl(tagIds).isEmpty()) return null;

        if (isAdd) {

            tagIds.forEach(tagId -> {
                ArticleTag tag = new ArticleTag();
                tag.setTagId(tagId);
                tag.setArticleId(articleId);
                articleTags.add(tag);
            });

            saveBatch(articleTags);

        } else {

            deleteArticleTagByArticleId(articleId);

            tagIds.forEach(tagId -> {
                ArticleTag tag = new ArticleTag();
                tag.setTagId(tagId);
                tag.setArticleId(articleId);
                articleTags.add(tag);
            });

            saveBatch(articleTags);

        }

        return articleTags;
    }

    @Override
    public Boolean deleteArticleTagByArticleId(Integer articleId) {

        LambdaQueryWrapper<ArticleTag> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ArticleTag::getArticleId, articleId);

        return remove(queryWrapper);
    }

    @Override
    public Map<Integer, Integer> getTagRefCountArticle() {

        QueryWrapper<ArticleTag> queryWrapper = new QueryWrapper<>();

        queryWrapper.select("count(article_id) as articleId,tag_id as tagId");
        queryWrapper.groupBy("tag_id");

        List<ArticleTag> list = list(queryWrapper);

        return list.stream().collect(Collectors.toMap(ArticleTag::getTagId, ArticleTag::getArticleId));

    }

    @Override
    public long getArticleCountByTagId(Integer tagId) {

        LambdaQueryWrapper<ArticleTag> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(ArticleTag::getTagId, tagId);

        return count(queryWrapper);
    }


}
